﻿using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.JSInterop;
using System.Net.Http.Headers;
using System.Net.Http;
using System.Text.Json;
using System.Text;
using System.Threading.Tasks;
using ImoviesBlazorAntPro.Shared;
using System.Net.Http.Json;


namespace ImoviesBlazorAntPro.Client.Auth
{
    public class AuthService : IAuthService
    {
        private readonly HttpClient _httpClient;
        private readonly AuthenticationStateProvider _authenticationStateProvider;
        private readonly ILocalStorageService _localStorage;

        public AuthService(HttpClient httpClient,
                           AuthenticationStateProvider authenticationStateProvider,
                           ILocalStorageService localStorage)
        {
            _httpClient = httpClient;
            _authenticationStateProvider = authenticationStateProvider;
            _localStorage = localStorage;
        }

        /// <summary>
        /// 注册用户
        /// </summary>
        /// <param name="registerModel"></param>
        /// <returns></returns>
        public async Task<RegisterResult> Register(RegisterModel registerModel)
        {
            var resp = await _httpClient.PostAsJsonAsync<RegisterModel>("api/accounts", registerModel);
            if (!resp.IsSuccessStatusCode)
            {
                return new RegisterResult { Successful = false };
            }
            return await resp.Content.ReadFromJsonAsync<RegisterResult>();
        }

        /// <summary>
        /// 登录用户
        /// </summary>
        /// <param name="loginModel"></param>
        /// <returns></returns>
        public async Task<LoginResult> Login(LoginModel loginModel)
        {
            var loginAsJson = JsonSerializer.Serialize(loginModel);
            var response = await _httpClient.PostAsync("api/Login", new StringContent(loginAsJson, Encoding.UTF8, "application/json"));
            var loginResult = JsonSerializer.Deserialize<LoginResult>(await response.Content.ReadAsStringAsync(), new JsonSerializerOptions { PropertyNameCaseInsensitive = true });

            if (!response.IsSuccessStatusCode)
            {
                return loginResult;
            }

            await _localStorage.SetItemAsync("authToken", loginResult.Token);
            await _localStorage.SetItemAsync("username", loginModel.UserName);
            //((ApiAuthenticationStateProvider)_authenticationStateProvider).MarkUserAsAuthenticated(loginModel.UserName, loginResult.Role);
            await ((ApiAuthenticationStateProvider)_authenticationStateProvider).MarkUserAsAuthenticatedAsync(loginModel.UserName);
            _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", loginResult.Token);

            return loginResult;
        }

        /// <summary>
        /// 注销登录
        /// </summary>
        /// <returns></returns>
        public async Task Logout()
        {
            await _localStorage.RemoveItemAsync("authToken");
            await _localStorage.RemoveItemAsync("username");
            ((ApiAuthenticationStateProvider)_authenticationStateProvider).MarkUserAsLoggedOut();
            _httpClient.DefaultRequestHeaders.Authorization = null;
        }


        /// <summary>
        /// 获取用户名
        /// </summary>
        /// <returns></returns>
        public async Task<string> GetUserName()
        {
            return await _localStorage.GetItemAsync("username") ?? string.Empty;
        }
    }
}
